import { Component, ViewChild } from '@angular/core';

import { Events, NavParams, Content, NavController } from 'ionic-angular';

import { ContactListService } from './list.service';

import { Storage } from '@ionic/storage';

import { Common } from '../../../providers/common';

import { ContactDetailPage } from '../detail/detail.component';

import { Config } from '../../../providers/config';

import _ from 'lodash';

@Component({
  selector: 'page-contact-list',
  templateUrl: 'list.html',
  providers: [ContactListService]
})
export class ContactListPage {
	moa_page_name: any = "page-contact-list";
  moa_page_explain: any = "通讯录";
  // 缓存通讯录数据
  storeListData: any;
  // 通讯录显示数据
  listData: any;
  // 查询字段
  queryText = "";
  // 右侧栏字母高度
  tagHeight = 0;
  // 头部标题+搜索框高度
  headerHeight = 0;
  // 展示内容高度
  displayHeight = 0;
  // 位移，可不管
  paddingTagHeight = 0;
  // 是否显示列表数据，解决性能问题
  isShowList = true;
  // 选中右侧字母，后出现的悬浮列表
  selectTag: any = {
    name: '',
    tag: []
  };
  selectTatName = "";
  // 所有的字母列表
  tagList: any = [];

  userToken = "";

  serverUrl =  "";

  _ = _;
  @ViewChild(Content) content: Content;

  constructor(
    public navParams: NavParams,
    public storage: Storage,
    public events: Events,
    public common: Common,
    public config: Config,
    public navCtrl: NavController,
    public contactListService: ContactListService
  ) {
    let that = this;
    this.initListData();
    this.events.unsubscribe('refresh-contact-list-on-keyboard-hide');
    // 监听键盘是否收起
    this.events.subscribe('refresh-contact-list-on-keyboard-hide', () => {
      that.updateList();
    });


    this.events.unsubscribe('hide-contact-tips-on-keyboard-show');
    // 监听键盘是否弹出
    this.events.subscribe('hide-contact-tips-on-keyboard-show', () => {
      that.hideTips();
    });

    this.storage.get('id_token').then((token) => {
      this.userToken = token;
      this.serverUrl = this.config.server;
    });
  }
  /**
   * [initListData 初始化列表数据]
   */
  initListData() {
    this.storage.get('contact-user-list').then(data => {
      if (data) {
        this.loadListData('local');
      } else {
        this.loadListData('server');
      }
    });
  };

  /**
   * [listHeader 控制列表header输出]
   * @param {[type]} record      [description]
   * @param {[type]} recordIndex [description]
   * @param {[type]} records     [description]
   */
  listHeader(record, recordIndex, records) {
    if (record.tag) {
      return record.tag;
    }
    return null;
  }
  /**
   * [loadListData 加载通讯录数据]
   * @param {[type]} type [local:加载本地，server：加载服务器]
   */
  loadListData(type) {
    this.queryText = "";
    this.content.scrollTo(0, 0, 100);
    this.hideTips();
    this.common.syncContactList(type).then((data: any) => {
      this.listData = data.listData;
      this.tagList = data.tagList;
      this.tagHeight = 0;
      this.ionViewDidEnter();
    })
  };
  /**
   * [function 点击汉字的时候，滚动列表到相应位置]
   * @param {[type]} name [description]
   */
  selectTagName = function(item) {
    this.selectTatName = item;
    let index = _.indexOf(this.selectTag.tag, item);
    this.content.scrollTo(0, this.selectTag.tagTop[index], 100);
  }
  /**
   * [scrollList 点击右侧字母，生成选择汉字条]
   * @param {[type]} tag [description]
   */
  scrollList(item) {
    this.selectTag = item;
    this.selectTatName = "";
    this.content.scrollTo(0, this.selectTag.sectionTop, 100);
  }
  /**
   * [goDetailPage 跳转详情页]
   * @param {[type]} item [description]
   */
  goDetailPage(item) {
    this.navCtrl.push(ContactDetailPage, item);
  }

  onSearchCancel(event) {
    this.queryText = "";
    this.updateList();
  }
  /**
   * [updateList 输入搜索内容，更新列表]
   */
  updateList() {
    this.hideTips();
    let qt = this.queryText.toLowerCase();
    this.content.scrollTo(0, 0, 100);
    if (this.queryText == '') {
      this.loadListData('local');
    } else {
      let tempList = [];
      this.storage.get('contact-user-list').then(data => {
        _.each(data, function(item, i) {
          if (item.emname.toLowerCase().indexOf(qt) > -1 || item.full_pinyin.indexOf(qt) > -1) {
            tempList.push(item);
          } else {
            let isPushToList = false;
            _.each(item.full_orgnames, function(orgname, ii) {
              if (orgname.pinyin && orgname.pinyin.indexOf(qt) > -1) {
                isPushToList = true;
              } else if (orgname.name.indexOf(qt) > -1) {
                isPushToList = true;
              }
            });
            if (isPushToList) {
              tempList.push(item);
            }
          }
        });
        this.listData = tempList;
      });
    }
  }

  /**
   * [hideTips 隐藏汉字选择条]
   */
  hideTips() {
    this.selectTag = {
      name: '',
      tag: []
    };
  };

  /**
   * [ionViewDidEnter 页面渲染完毕后，计算显示位置]
   */
  ionViewDidEnter() {
    let that = this;
    // this.isShowList= true;
    if (this.tagHeight == 0) {
      this.headerHeight = document.getElementById("contact-list-header").offsetHeight;
      let tabsHeight = (document.getElementsByClassName("tabbar")[0])['offsetHeight'];
      this.paddingTagHeight = this.headerHeight - tabsHeight;
      this.displayHeight = this.content.contentHeight;
      // this.tagHeight = this.displayHeight / 26;
      this.tagHeight = this.displayHeight / (this.tagList.length + 1);
      setTimeout(function() {
        var obj = document.getElementsByClassName("contact-bar-item");
        _.each(obj, function(item, index) {
          item.addEventListener('touchmove', function(e) {
            var target = document.elementFromPoint(e.touches[0].pageX, e.touches[0].pageY);
            if (target) {
              let selectItem = _.find(that.tagList, {
                name: target['innerText'].toLowerCase().trim()
              });
              if (selectItem) {
                that.scrollList(selectItem);
              }
            }
          }, false);
        });
      }, 1000);
    }
  }

}
